/* tslint:disable:no-console */
import React, { useState } from 'react'
import { Text, TouchableOpacity, View, StyleSheet, useWindowDimensions, TextInput, ActivityIndicator } from 'react-native'
import { Toast } from '@ant-design/react-native'
import { connect } from 'react-redux'
import { SetUserInfo, SetToken } from "../../redux/features/appSlice"
import { pTx } from "../../utils/dimensions"
import { importMnemonic, importPrivateKey, signMessage } from 'react-native-web3-wallet';
import { TabView, SceneMap, TabBar } from 'react-native-tab-view';
import { useRealm } from '@realm/react'
import { schemaName } from "../../realm"
import loadFromLocalStorages from "../../loadFromLocalStorages"
import ShadowCard from "../../utils/shadowCard"
import LinearGradient from 'react-native-linear-gradient';
import httpApi from "../../api"
import Realm from "realm"
import AsyncStorage from '@react-native-async-storage/async-storage';

const mapStateToProps = state => {
    return {
    }
}



const ImportWallet = (props) => {
    const layout = useWindowDimensions();
    const [index, setIndex] = useState(0);
    const [routes] = useState([
        { key: 'first', title: '助记词' },
        { key: 'second', title: '私钥' },
    ]);
    const [privateKey, setPrivateKey] = useState('')
    const [mnemonic, setMnemonic] = useState("")
    const [loading, setLoading] = useState(false)
    const realm = useRealm();
    const { loadInitialData } = loadFromLocalStorages()

    const FinishCreateWallet = async () => {
        if (!mnemonic) return
        try {
            setLoading(true)
            const res = await importMnemonic(mnemonic, props.route.params.password)
            const { address, keystore } = res
            const sign = await signMessage(
                JSON.stringify(keystore),
                props.route.params.password,
                httpApi.message,
            )
            await sendLogin(sign, address, keystore, 1)
        } catch (error) {
            Toast.info(error)
        }
    }

    const FinishCreateWallet2 = async () => {
        if (!privateKey) return
        try {
            setLoading(true)
            const res = await importPrivateKey(privateKey, props.route.params.password)
            const { address, keystore } = res
            const sign = await signMessage(
                JSON.stringify(keystore),
                props.route.params.password,
                httpApi.message,
            )
            await sendLogin(sign, address, keystore, 2)
        } catch (error) {
            Toast.info(error)
        }
    }

    const sendLogin = async (sign, address, keystore, type) => {
        try {
            const login = await httpApi.login({
                signature: sign,
                message: httpApi.message
            })
            if (login.code == 20) {
                realm.write(() => {
                    realm.create(schemaName.UserInfo, { ...login.data.UserInfo, Token: login.data.Token, Current: true }, true);
                    realm.create(schemaName.Wallet, {
                        _id: new Realm.BSON.UUID(),
                        address,
                        keystore: JSON.stringify(keystore),
                        type,
                        name: "BNB-1",
                        current: true,
                        state: 1
                    }, true);
                });
                AsyncStorage.setItem('token', login.data.Token)
                await loadInitialData()
            } else {
                const register = await httpApi.register({
                    nickname: "BNB-1",
                    signature: sign,
                    message: httpApi.message,
                    profilePhoto: httpApi.defaultAvatar
                })
                if (register.code == 20) {
                    realm.write(() => {
                        realm.create(schemaName.UserInfo, { ...register.data.UserInfo, Token: register.data.Token, Current: true }, true);
                        realm.create(schemaName.Wallet, {
                            _id: new Realm.BSON.UUID(),
                            address,
                            keystore: JSON.stringify(keystore),
                            type,
                            name: "BNB-1",
                            current: true,
                            state: 1
                        }, true);
                    });
                    AsyncStorage.setItem('token', register.data.Token)
                    props.navigation.navigate('personalInfo')
                }
            }
        } catch (error) {
            Toast.info(error)
        }
        setLoading(false)
    }

    const FirstRoute = () => (
        <>
            <View style={{ flex: 1, }} >
                <TextInput
                    value={mnemonic}
                    style={styles.TextareaItem}
                    rows={7}
                    placeholder="输入助记词"
                    multiline={true}
                    onChangeText={value => setMnemonic(value)} />
            </View>
            <View style={styles.footerButton}>
                <ShadowCard style={styles.button}>
                    <LinearGradient
                        colors={['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)']}
                        start={{ x: 0.25, y: 0.25 }}
                        end={{ x: 0.75, y: 0.75 }}
                        style={styles.linearGradient}
                    >
                        <TouchableOpacity disabled={loading} style={[styles.import, styles.button]} onPress={FinishCreateWallet}>
                            <>
                                {loading ? <ActivityIndicator /> : ""}
                                <Text style={styles.ButtonText}>导入钱包</Text>
                            </>
                        </TouchableOpacity>
                    </LinearGradient>
                </ShadowCard>
            </View>
        </>
    );

    const SecondRoute = () => (
        <>
            <View style={{ flex: 1, }} >
                <TextInput
                    value={privateKey}
                    style={styles.TextareaItem}
                    rows={7}
                    placeholder="输入私钥"
                    multiline={true}
                    onChangeText={value => setPrivateKey(value)} />
            </View>
            <View style={styles.footerButton}>
                <ShadowCard style={styles.button}>
                    <LinearGradient
                        colors={['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)']}
                        start={{ x: 0.25, y: 0.25 }}
                        end={{ x: 0.75, y: 0.75 }}
                        style={[styles.linearGradient]}>
                        <TouchableOpacity disabled={loading} style={[styles.import, styles.button]} onPress={FinishCreateWallet2}>
                            <>
                                {loading ? <ActivityIndicator /> : ""}
                                <Text style={styles.ButtonText}>导入钱包</Text>
                            </>
                        </TouchableOpacity>
                    </LinearGradient>
                </ShadowCard>
            </View>
        </>
    );

    const renderScene = SceneMap({
        first: FirstRoute,
        second: SecondRoute,
    });

    renderTabBar = (props) => {
        return (
            <View style={{}}>
                <TabBar
                    {...props}
                    style={{
                        backgroundColor: '#fff',
                    }}
                    activeColor={'#0A0C14'}
                    inactiveColor={'#0A0C14'}
                    indicatorStyle={{
                        backgroundColor: '#06C161',
                        elevation: 10,
                    }}
                    renderLabel={({ route, focused, color }) => (
                        <Text
                            style={{
                                fontWeight: focused ? 'bold' : 'normal',
                                color,
                                fontSize: pTx(16)
                            }}>
                            {route.title}
                        </Text>
                    )}
                />
            </View>
        );
    }

    return (
        <View style={{ paddingHorizontal: pTx(16), flex: 1, }}>
            <TabView
                renderTabBar={this.renderTabBar}
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={setIndex}
            />
        </View>
    );
}
export default connect(mapStateToProps, { SetToken, SetUserInfo })(ImportWallet)

const styles = StyleSheet.create({
    tabBar: {
        flexDirection: 'row',
    },
    TextareaItem: {
        marginTop: pTx(30),
        padding: pTx(15),
        borderColor: "rgba(114, 114, 114, 1)",
        borderWidth: 1,
        textAlignVertical: "top",
        borderRadius: pTx(12),
    },
    footerButton: {
        paddingTop: pTx(15),
        paddingBottom: pTx(63),
        alignItems: "center"
    },
    linearGradient: {
        borderRadius: 10
    },
    button: {
        width: pTx(303),
        height: pTx(55),
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
    },
    ButtonText: {
        color: "rgba(10, 12, 20, 1)",
        fontSize: pTx(14),
        fontWeight: 'bold'
    },

})
